# -*- encoding: utf-8 -*-
"""
File Name: redis_alarm_manager
Description:
Author : 'lirui'
date: 2024/2/8
Contact: marjey_lee@163.com
Change Activity:
2024/2/8:
"""
import json
from ll.third_party.redis_util.redis_client import RedisClient
from projects.monitoring.alarm_manager.config.config import REDIS_SERVER_INFO
from projects.monitoring.common.do.alarm import Alarm


class RedisAlarmManager:
    """
    load all redis alarm problems.
    """

    def __init__(
            self,
            host=REDIS_SERVER_INFO['host'],
            port=REDIS_SERVER_INFO['port']
    ):
        self.host = host
        self.port = port
        self.redis_client = self._init_client()

    def _init_client(self):
        """
        init client.
        """
        return RedisClient(host=self.host, port=self.port)

    def close(self):
        """

        Returns:

        """

    def get(self, key):
        """

        """
        return self.redis_client.get(key)

    def set(self, key, value):
        self.redis_client.insert(key, value)

    def load_current_problems(self, redis_key):
        """

        """
        res = self.redis_client.get(redis_key)
        if res is None:
            res = {}
        else:
            res = str(res, 'utf8')
            res = json.loads(res)
            new_res = {}
            for k, r in res.items():
                alarm = Alarm.json_to_obj(r)
                new_res[k] = alarm
            res = new_res
        return res

    def refresh_redis_problems(
            self,
            subscribe_problems,
            redis_key
    ):
        """

        """
        # subscribe_problems = {}
        new_problems = {}
        recovery_problems = {}
        redis_problems = self.load_current_problems(redis_key)
        # redis_problems = {}
        for key, alarm in subscribe_problems.items():
            if key not in redis_problems:
                new_problems[key] = alarm
        for key, alarm in redis_problems.items():
            if key not in subscribe_problems:  # not
                recovery_problems[key] = alarm
        self.refresh_redis(
            subscribe_problems,
            redis_key
        )
        return new_problems, recovery_problems

    def refresh_redis(
            self,
            subscribe_problems,
            redis_key
    ):
        json_obj_mapping = {}
        for key, sub in subscribe_problems.items():
            json_obj = sub.to_json()
            json_obj_mapping[key] = json_obj
        self.redis_client.insert(redis_key, json_obj_mapping)
        return json_obj_mapping


REDIS_ALARM_MANAGER = RedisAlarmManager()
